package com.aduerr.v1shouyin.mvp.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.entity.MemberInfoEntity;
import com.aduerr.v1shouyin.entity.MemberToPayEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.util.LogUtils;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MemberInfoActivity extends AppCompatActivity {

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.tv_ordermoney)
    TextView tvOrdermoney;
    @BindView(R.id.tv_member_name)
    TextView tvMemberName;
    @BindView(R.id.tv_zhekou)
    TextView tvZhekou;
    @BindView(R.id.tv_balance)
    TextView tvBalance;
    @BindView(R.id.tv_integral)
    TextView tvIntegral;
    @BindView(R.id.tv_confrom)
    TextView tvConfrom;
    SweetAlertDialog pDialog;
    private MemberInfoEntity memberInfoEntity;
    private String realMoney;
    private String scanMemberNo;
    private String showtype;
    private String beizhu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_member_info);
        ButterKnife.bind(this);
        initDate();
        initUI();
    }


    private void initDate() {
        Intent intent = getIntent();
        if(intent != null) {
            memberInfoEntity = (MemberInfoEntity) intent.getSerializableExtra(
                    "memberinfo");
            realMoney = intent.getStringExtra("realMoney");
            LogUtils.e("realMoney", realMoney);
            scanMemberNo = intent.getStringExtra("scanMemberNo");
            showtype = intent.getStringExtra("showtype");
            beizhu = intent.getStringExtra("beizhu");
        }
    }

    private void initUI() {
        tvConfrom.setEnabled(true);

        tvTitle.setText("会员消费");
        if(realMoney != null) {
            tvOrdermoney.setText(realMoney);
        }
        if(showtype.equals("0")) {//余额不足的情况

            tvConfrom.setVisibility(View.GONE);
        } else {//余额充值的情况

            tvConfrom.setVisibility(View.VISIBLE);

        }

        if(memberInfoEntity != null) {
            if(memberInfoEntity.getData() != null) {
                tvMemberName.setText(memberInfoEntity.getData().getNames());
                // TODO: 2017/12/11 0011  折扣的信息
                tvZhekou.setText(memberInfoEntity.getData().getDiscount());
                tvBalance.setText(memberInfoEntity.getData().getBalance());
                tvIntegral.setText(memberInfoEntity.getData().getIntegral());
            }
        }

    }


    @OnClick({R.id.img_back, R.id.tv_confrom})
    public void onViewClicked(View view) {
        switch(view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.tv_confrom:
                tvConfrom.setEnabled(false);

                // TODO: 2017/12/11 0011 请求会员消费接口
                toHuiyuanMoney(scanMemberNo, realMoney);
                break;
        }
    }


    private void toHuiyuanMoney(String erWeiMaResult, String realMoney) {
        if(TextUtils.isEmpty(realMoney)) return;
        if(!isNumeric(erWeiMaResult)) return;
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("scanmemberno", erWeiMaResult);
        addParams.put("paymoney", "-" + realMoney);
        APIRetrofit.getAPIService().MemberToPay(RXRequest.getXingPosParams(addParams,
                this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<MemberToPayEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        if(pDialog == null) {
                            pDialog = new SweetAlertDialog(MemberInfoActivity.this,
                                    SweetAlertDialog.PROGRESS_TYPE);
                            pDialog.getProgressHelper().setBarColor(Color.parseColor(
                                    "#005fee"));
                            pDialog.setTitleText("正在付款中");
                            pDialog.setCancelable(false);
                            pDialog.show();
                        }
                    }

                    @Override
                    public void onNext(@NonNull MemberToPayEntity memberToPayEntity) {
//                        if (Tools.isAvailable(memberToPayEntity)) return;
                        int success = memberToPayEntity.getSuccess();
                        if(success == 1) {
                            Intent intent = new Intent(MemberInfoActivity.this,
                                    ResultActivity.class);
                            intent.putExtra("money",
                                    memberToPayEntity.getData().getChangemoney().replace("-", ""));
                            intent.putExtra("beizhu", beizhu);
                            intent.putExtra("sucess", "6");
                            intent.putExtra("scanMemberNo", erWeiMaResult);
                            if(memberInfoEntity != null) {
                                intent.putExtra("memberInfoEntity", memberInfoEntity);
                            }
                            intent.putExtra("datebeen", memberToPayEntity);
                            // TODO: 2018/1/19 0019 再次请求会员详情的数据然后一并传入到resultactivity中
//                            toScanMemberInfor(erWeiMaResult, realMoney, beizhu, "6",
//                            memberToPayEntity);
                            startActivity(intent);
                            finish();
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            SharedPreferencesUtils.remove(MemberInfoActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(MemberInfoActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(MemberInfoActivity.this,
                                    BangGuidActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(memberToPayEntity.getErrMsg());
                            SharedPreferencesUtils.remove(MemberInfoActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(MemberInfoActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(MemberInfoActivity.this,
                                    LoginActivity.class));
                            finish();
                        } else {
                            ToastUtils.showToast(MemberInfoActivity.this,
                                    "" + memberInfoEntity.getErrMsg());
                            Intent intent = new Intent(MemberInfoActivity.this,
                                    ResultActivity.class);
                            intent.putExtra("money", realMoney);
                            intent.putExtra("sucess", "0");
                            startActivity(intent);
                            finish();
                        }

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if(pDialog != null) {
                            pDialog.dismiss();
                            pDialog = null;
                        }
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(MemberInfoActivity.this, "网络连接超时",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(MemberInfoActivity.this, "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MemberInfoActivity.this,
                                    e.getMessage().toString(), Toast.LENGTH_SHORT).show();
                        }
                        Intent intent = new Intent(MemberInfoActivity.this,
                                ResultActivity.class);
                        intent.putExtra("money", realMoney);
                        intent.putExtra("sucess", "0");
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    public void onComplete() {
                        if(pDialog != null) {
                            pDialog.dismiss();
                            pDialog = null;
                        }

                    }
                });
    }

    /**
     * 利用正则表达式判断字符串是否是数字
     *
     * @param str
     * @return
     */

    public boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if(!isNum.matches()) {
            return false;
        }
        return true;
    }

    //会员重新获取信息为了打印余额
    private void toScanMemberInfor(String erWeiMaResult, String realMoney,
                                   String beizhu, String sucess,
                                   MemberToPayEntity memberToPayEntity) {
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("scanMemberNo", erWeiMaResult);
        APIRetrofit.getAPIService().getMemberinfo(RXRequest.getXingPosParams(addParams,
                this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(memberInfoEntity1 -> {
//                    if (Tools.isAvailable(memberInfoEntity1)) return;
                    int success = memberInfoEntity.getSuccess();
                    if(success == 1) {
                        Intent intent = new Intent(MemberInfoActivity.this,
                                ResultActivity.class);
                        intent.putExtra("money", realMoney);
                        intent.putExtra("beizhu", beizhu);
                        intent.putExtra("sucess", sucess);
                        intent.putExtra("scanMemberNo", erWeiMaResult);
                        if(memberInfoEntity != null) {
                            intent.putExtra("memberInfoEntity", memberInfoEntity);
                        }
                        intent.putExtra("datebeen", memberToPayEntity);
                        startActivity(intent);
                        finish();
                    } else {
                        ToastUtils.showToast(MemberInfoActivity.this,
                                memberInfoEntity.getErrMsg() + "");
                    }
                }, throwable -> {

                });

    }


}
